package cn.itsource.pethome.user.controller;
import cn.itsource.pethome.base.domain.AjaxResult;
import cn.itsource.pethome.base.domain.Repeat;
import cn.itsource.pethome.base.util.RedisService;
import cn.itsource.pethome.user.domain.User;
import cn.itsource.pethome.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Class_Name: UserController
 * @author: maizi
 * @Description:
 * @Date: 12:33 2022/2/25
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisService redisService;
    /**
     * 手机号注册的接口
     * @param user
     * @return
     */
    @PostMapping("/phoneRegister")
    public AjaxResult<User> phoneRegister(@RequestBody @Validated(User.PhoneRegister.class) User user){
        userService.insert(user);
        return AjaxResult.me ();
    }
    /**
     * 手机号校验
     * url:/user/checkphone/"+this.user.phone
     * 参数:String phone 在路径上
     * 返回值:AjaxResult
     */
    @GetMapping("/checkphone/{phone}")
    public AjaxResult checkPhone(@PathVariable("phone") String phone){
        userService.checkPhone(phone);
        return AjaxResult.me ();
    }
    /**
     * url:/user/sendmobilecode/"+this.user.phone
     * 参数:String phone 在路径上
     * 返回值:AjaxResult
     */
    @GetMapping("/sendmobilecode/{phone}")
    public AjaxResult sendPhoneCode(@PathVariable("phone")String phone, HttpServletRequest request){
        // 获取当前方法的方法名称
        //Thread.currentThread() .getStackTrace()[1].getMethodName()
        //如果当前redis 存在该key,说明一分钟内该用户已经请求该接口,所以不能重复提交
        //request.getRemoteAddr () 获取用户ip
        //request.getRequestURI() 获取 用户访问的url
        if (redisService.hasKey (request.getRemoteAddr ()+request.getRequestURI())){
            throw new RuntimeException ("哥哥,你太快了");
        }
        //将该用户ip存入
        redisService.setStringKeyAndValue (request.getRemoteAddr ()+request.getRequestURI(), request.getRemoteAddr (),1);
        //走正常业务逻辑
        userService.sendPhoneCode(phone);
        return AjaxResult.me ();
    }

    @Repeat(value = 5)
    @GetMapping("test")
    public  String  test(){

       return  "测试重复提交注解";
    }
}
